package com.learn.Chapter1_1_2.Controller;

import com.entity.User;
import com.learn.Chapter1_1_2.dto.Error;
import com.learn.Chapter1_1_2.Exception.UserNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created by zhaoben on 2016/12/16.
 */
@RestController
@RequestMapping("/userUp")
public class UserControllerUpper {Map<String,User> userDB = Collections.synchronizedMap(new HashMap<String, User>());

    @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json")
    public User getUserById(@PathVariable("id") String id){
        User result = userDB.get(id);
        if(result == null){
           throw new UserNotFoundException(id);
        }
        return result;
    }

    @RequestMapping(value="/save", method=RequestMethod.POST, consumes = "application/json")
    public ResponseEntity<String> saveUser(@RequestBody List<User> users){
        for (User user: users) {
            userDB.put(user.getId(),user);
        }
        return new ResponseEntity<String>("save is ok!", HttpStatus.OK);
    }

    @RequestMapping(value="/",method = RequestMethod.GET, produces = "application/json")
    public List<User> getAll(){
        Collection<User> result = userDB.values();
        if(result.size() == 0){
            throw new UserNotFoundException();
        }
        return new ArrayList<>(result);
    }

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<Error> UserNotFound(UserNotFoundException e){
        String userId = e.getId();
        Error error = new Error(404 , "User （"+userId+") not found");
        return new ResponseEntity<Error>(error, HttpStatus.NOT_FOUND);
    }
}
